#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2020/12/11 10:22
    Desc  :     分液器
--------------------------------------
"""
from flask_mongoengine import Pagination, json
from mongoengine import QuerySet
import json


class PaginationUtils:

    def __init__(self, iterable, page:int, size:int):
        self.iterable = iterable
        self.page = 1 if page is None or page == '' else int(page)
        self.size = 10 if size is None or size == '' else int(size)

    @property
    def items(self):
        pagination = Pagination(self.iterable, page = self.page, per_page = self.size)
        return {
            'array': pagination.items,
            'page': self.page,
            'size': self.size,
            'totalsize': pagination.total,
        }


class ListPaginationUtils:

    def __init__(self, queryset, **kwargs):
        self.queryset = queryset
        self.page = 1 if kwargs.get('page') is None or kwargs.get('page') == '' else int(kwargs.get('page'))
        self.size = 10 if kwargs.get('size') is None or kwargs.get('size') == '' else int(kwargs.get('size'))
        self.pagination = None

    @property
    def items(self):
        if isinstance(self.queryset, QuerySet):
            total = self.queryset.count()
            # pagination = self.queryset.skip((self.page -1) * self.size).limit(self.size)

            self.pagination = self.jsonArray()
        else:
            self.pagination = json.loads(self.queryset)
            total = len(self.pagination)

        return {
            'array': self.pagination,
            'page': self.page,
            'size': self.size,
            'totalsize': total,
        }

    # 自定义返回列表
    def jsonArray(self):
        pagination = self.queryset.skip((self.page -1) * self.size).limit(self.size)
        paginationList = []
        for i in pagination:
            if i.to_json() and isinstance(i.to_json(), dict):
                paginationList.append(i.to_json())
            else:
                paginationList.append(i)
        return paginationList

    # 其他类型返回格式
    def valueArray(self):
        pagination = self.queryset.skip((self.page -1) * self.size).limit(self.size)
        paginationList = []
        for i in pagination:
            if i.value_label() and isinstance(i.value_label(), dict):
                paginationList.append(i.value_label())
            else:
                paginationList.append(i)
        return paginationList